<template>
  <div id="aCoursesList" class="bg-fa of">
    <!-- /课程详情 开始 -->
    <section class="container">
      <section class="path-wrap txtOf hLh30">
        <a href="#" title class="c-999 fsize14">首页</a>
        \
        <a href="#" title class="c-999 fsize14">{{
            courseWebVo.subjectLevelOne
          }}</a>
        \
        <span class="c-333 fsize14">{{ courseWebVo.subjectLevelTwo }}</span>
      </section>
      <div>
        <article class="c-v-pic-wrap" style="height: 357px">
          <section class="p-h-video-box" id="videoPlay">
            <!-- //TODO: 图片显示效果待优化 -->
            <img
              :src="courseWebVo.cover"
              :alt="courseWebVo.title"
              style="height: 357px"
              class="dis c-v-pic"
            />
          </section>
        </article>
        <aside class="c-attr-wrap">
          <section class="ml20 mr15">
            <h2 class="hLh30 txtOf mt15">
              <span class="c-fff fsize24">{{ courseWebVo.title }}</span>
            </h2>
            <section class="c-attr-jg"></section>
            <section class="c-attr-mt c-attr-undis">
              <span class="c-fff fsize14"
              >主讲： {{ courseWebVo.teacherName }}&nbsp;&nbsp;&nbsp;</span
              >
            </section>
            <section class="c-attr-mt of">
              <span class="ml10 vam">
                <em class="icon18 scIcon"></em>
                <a
                  v-if="ischoice"
                  class="c-fff vam"
                  title="点击查看我收藏的课程"
                  :href="'/ucenter/myCourse/' + loginInfo.id"
                >已收藏</a
                >
                <a
                  v-else
                  class="c-fff vam"
                  title="收藏"
                  href="#"
                  @click="addMycourse()"
                >收藏</a
                >
              </span>
            </section>
            <section class="c-attr-mt">
              <a href="#" title="立即观看" class="comm-btn c-btn-3">立即观看</a>
            </section>
          </section>
        </aside>
        <aside class="thr-attr-box">
          <ol class="thr-attr-ol clearfix">
            <li>
              <p>&nbsp;</p>
              <aside>
                <!-- //TODO: 学习次数位数一大显示效果有问题 -->
                <span class="c-fff f-fM">学习人数</span>
                <br/>
                <h6 class="c-fff f-fM mt10">{{ courseWebVo.choiceCount }}</h6>
              </aside>
            </li>
            <li>
              <p>&nbsp;</p>
              <aside>
                <span class="c-fff f-fM">课时数</span>
                <br/>
                <h6 class="c-fff f-fM mt10">{{ courseWebVo.lessonNum }}</h6>
              </aside>
            </li>
            <li>
              <p>&nbsp;</p>
              <aside>
                <span class="c-fff f-fM">浏览数</span>
                <br/>
                <h6 class="c-fff f-fM mt10">{{ courseWebVo.viewCount }}</h6>
              </aside>
            </li>
          </ol>
        </aside>
        <div class="clear"></div>
      </div>
      <!-- /课程封面介绍 -->
      <div class="mt20 c-infor-box">
        <article class="fl col-7">
          <section class="mr30">
            <div class="i-box">
              <div>
                <section id="c-i-tabTitle" class="c-infor-tabTitle c-tab-title">
                  <a name="c-i" class="current" title="课程详情">课程详情</a>
                </section>
              </div>
              <article class="ml10 mr10 pt20">
                <div>
                  <h6 class="c-i-content c-infor-title">
                    <span>课程介绍</span>
                  </h6>
                  <div class="course-txt-body-wrap">
                    <section class="course-txt-body">
                      <!-- 翻译html -->
                      <p v-html="courseWebVo.description">
                        {{ courseWebVo.description }}
                      </p>
                    </section>
                  </div>
                </div>
                <!-- /课程介绍 -->
                <div class="mt50">
                  <h6 class="c-g-content c-infor-title">
                    <span>课程大纲</span>
                  </h6>
                  <section class="mt20">
                    <div class="lh-menu-wrap">
                      <menu id="lh-menu" class="lh-menu mt10 mr10">
                        <ul>
                          <!-- 文件目录 遍历章节和小节 -->
                          <li
                            class="lh-menu-stair"
                            v-for="chapter in chapterVideoList"
                            :key="chapter.id"
                          >
                            <a
                              href="javascript: void(0)"
                              :title="chapter.title"
                              class="current-1"
                            >
                              <em class="lh-menu-i-1 icon18 mr10"></em
                              >{{ chapter.title }}
                            </a>

                            <ol class="lh-menu-ol" style="display: block">
                              <li
                                class="lh-menu-second ml30"
                                v-for="video in chapter.children"
                                :key="video.id"
                              >
                                <nuxt-link
                                  :to="{
                                    name: 'player-vid',
                                    params: {
                                      vid: video.videoSourceId,
                                    },
                                    query: {
                                      courseId: courseWebVo.id,
                                    },
                                  }"
                                  target="_blank"
                                >
                                  <span class="fr">
                                    <i class="free-icon vam mr10">开始播放</i>
                                  </span>
                                  <em class="lh-menu-i-2 icon16 mr5">&nbsp;</em
                                  >{{ video.title }}
                                </nuxt-link>
                              </li>
                            </ol>
                          </li>
                        </ul>
                      </menu>
                    </div>
                  </section>
                </div>
                <!-- /课程大纲 -->
              </article>
            </div>
          </section>
        </article>
        <aside class="fl col-3">
          <div class="i-box">
            <div>
              <section class="c-infor-tabTitle c-tab-title">
                <a title href="javascript:void(0)">主讲讲师</a>
              </section>
              <section class="stud-act-list">
                <ul style="height: 100%">
                  <li style="height: 100%">
                    <div class="u-face">
                      <a href="#">
                        <img
                          :src="courseWebVo.avatar"
                          width="50"
                          height="50"
                          alt
                        />
                      </a>
                    </div>
                    <section class="hLh30 txtOf">
                      <a class="c-333 fsize16 fl" href="#">{{
                          courseWebVo.teacherName
                        }}</a>
                    </section>
                    <section class="hLh20 txtOf">
                      <span class="c-999">{{ courseWebVo.intro }}</span>
                    </section>
                  </li>
                </ul>
              </section>
            </div>
          </div>
        </aside>
        <div class="clear"></div>
      </div>
      <!-- //TODO美化课程评论模块-->
      <div class="comment-wrapper">
        <div class="comment-content">
          <h6 class="c-c-content c-infor-title" id="i-art-comment">
            <span class="commentTitle">课程评论</span>
          </h6>
          <section class="no-data-wrap" v-if="commentAndUserList.length == 0">
            <em class="icon30 no-data-ico">&nbsp;</em>
            <span class="c-666 fsize14 ml10 vam"
            >该课程还没有评论，赶紧发表第一个评论吧</span>
          </section>
          <div
            v-for="(item, index) in currentPageData"
            :key="index"
            style="font-size: 15px"
            class="comments-item"
          >
            <div class="comments-info">
              <div class="commenter-info">
                <a-avatar slot="avatar" :src="item.avatar"/>
                <span style="color: #2d9aff"> {{ item.nickname }} </span>
                <el-divider direction="vertical"></el-divider>
                <span style="margin-left: 5px"> {{ item.content }}</span>
              </div>
              <div slot="action" class="action">
                <el-button
                  type="text"
                  @click="showCommentInput(item)"
                  class="el-icon-message"
                >
                  回复
                </el-button>
                <div class="el-icon-date">
                  {{ momentFormat(item.createTime)  }}
                </div>
              </div>
            </div>

            <div v-if="item.childList" class="reply">
              <list
                :list="item.childList"
                :comment="item"
                v-on:showCommentInput="showCommentInput"
              ></list>
            </div>
          </div>
          <br/>
          <footer v-if="commentAndUserList.length > 0">
            <div class="paging">
              <a type="primary" plain @click="prevPage()"> < </a>
              <a
                v-for="n in totalPage"
                :key="n"
                :class="{
                  current: page == n,
                  undisable: page == n,
                }"
                :title="'第' + n + '页'"
                href="#"
                @click.prevent="currentPage(n)"
              >{{ n }}</a
              >
              <a type="primary" plain @click="nextPage()"> &gt; </a>
              <span>第{{ page }}页/共{{ totalPage }}页</span>
            </div>

            <!--          <div class="comment-page">-->
            <!--            <el-pagination-->
            <!--              background-->
            <!--              :hide-on-single-page="true"-->
            <!--              layout="prev, pager, next"-->
            <!--              :page-count="totalPage"-->
            <!--              :current-page="page"-->
            <!--              @prev-click="prevPage"-->
            <!--              @next-click="nextPage"-->
            <!--            >-->
            <!--            </el-pagination>-->
            <!--          </div>-->
          </footer>
          <div id="target">
            <section class="lh-bj-list pr mt20 replyhtml">
              <ul>
                <li class="unBr">
                  <aside class="noter-pic">
                    <img
                      width="50"
                      height="50"
                      class="picImg"
                      src="~/assets/img/avatar-boy.gif"
                    />
                  </aside>
                  <div class="of">
                    <section class="n-reply-wrap">
                      <fieldset>
                        <textarea
                          name=""
                          v-model="comment.content"
                          :placeholder="placeholders"
                          id="commentContent"
                        ></textarea>
                      </fieldset>
                      <p class="of mt5 tar pl10 pr10">
                        <span class="fl"
                        ><tt
                          class="c-red commentContentmeg"
                          style="display: none"
                        ></tt
                        ></span>
                        <el-button @click="cancel" round>清空</el-button>
                        <el-button
                          type="primary"
                          @click="addComment()"
                          icon="el-icon-message"
                          round
                        >回复
                        </el-button
                        >
                      </p>
                    </section>
                  </div>
                </li>
              </ul>
            </section>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import courseApi from "@/api/course";
import mycourseApi from "@/api/mycourse";
import messageApi from "@/api/message";
import List from "@/components/List";
import commentApi from "@/api/comment";
import cookie from "js-cookie";
import "@/assets/css/article.less";
import historyApi from "@/api/history";
import moment from "moment";
moment.locale('zh-cn')
export default {
  asyncData({params, error}) {
    return {courseId: params.id};
  },
  data() {
    return {
      commentAndUserList: [],
      currentPageData: [], //当前页显示内容
      totalPage: 1, // 统共页数，默认为1
      placeholders: "写下你的评论",
      page: 1,
      limit: 4,
      comment: {
        content: "",
        relatedId: "",
        parentId: "0",
      },
      mycourse: {
        courseId: "",
      },
      loginInfo: {
        id: "",
        age: "",
        avatar: "",
        mobile: "",
        nickname: "",
        sex: "",
      },
      courseInfo: {},
      courseWebVo: {},
      chapterVideoList: [],
      ischoice: false,
      message: {
        content: "",
        memberId: "0",
        senderName: "",
        link: "",
        type: 0,
      },
      history: {
        userId: "",
        cover: "",
        urlPath: "",
        title: "",
        tag: ""
      }
    };
  },
  created() {
    this.initCourseInfo();
    this.initComment();
  },
  mounted() {
    this.learnCourse()
  },
  methods: {
    initCourseInfo() {
      //从cookie获取用户信息
      var userStr = cookie.get("dhu_ucenter");
      // 把字符串转换json对象(js对象)
      if (userStr) {
        this.loginInfo = JSON.parse(userStr);
      }
      courseApi.getCourseInfo(this.courseId).then((response) => {
        this.courseWebVo = response.data.data.courseWebVo
        this.chapterVideoList = response.data.data.chapterVideoList
        this.ischoice = response.data.data.isChoice
        this.collectData()
      });
    },
    initComment() {
      commentApi.getCoursePageList(this.courseId).then((response) => {
        this.commentAndUserList = response.data.data.list;
        this.totalPage = Math.ceil(this.commentAndUserList.length / this.limit);
        this.totalPage = this.totalPage == 0 ? 1 : this.totalPage;
        this.setCurrentPageData();
      });
    },
    addComment() {
      console.log("add");
      this.comment.relatedId = this.courseId;
      this.message.content = this.comment.content;
      this.message.senderName = this.loginInfo.nickname;
      commentApi.addCourseComment(this.comment).then((response) => {
        if (response.data.success) {
          this.$message.success("评论成功");
          if (this.comment.parentId != "0") {
            //没有父评论，不回复
            this.message.type = 1;
            messageApi.messageNotify(this.message).then((response) => {
            });
          }
          this.message.memberId = "0";
          this.comment.content = "";
          this.placeholders = "写下你的评论";
          if (
            this.commentAndUserList.length % 4 == 0 &&
            this.commentAndUserList.length != 0 &&
            this.comment.parentId == "0"
          )
            this.page = this.totalPage + 1;
          else if (this.comment.parentId == "0") this.page = this.totalPage;
          this.comment.parentId = "0";
          this.initComment();
        }
      });
    },
    setCurrentPageData() {
      let begin = (this.page - 1) * this.limit;
      let end = this.page * this.limit;
      this.currentPageData = this.commentAndUserList.slice(begin, end);
    },
    currentPage(val) {
      this.page = val;
      this.setCurrentPageData();
    },
    prevPage() {
      if (this.page == 1) return;

      this.page--;
      this.setCurrentPageData();
    },
    // 下一页
    nextPage() {
      if (this.page == this.totalPage) return;

      this.page++;
      this.setCurrentPageData();
    },
    cancel() {
      this.comment.content = "";
      this.placeholders = "写下你的评论";
      this.comment.parentId = "0";
      this.message.memberId = "0";
    },
    showCommentInput(reply) {
      if (reply) {
        this.placeholders = "@" + reply.nickname + " ";
      } else {
        this.inputComment = "";
      }
      //当点击了回复时，页面滚动到评论框的位置
      document.getElementById("target").scrollIntoView();
      this.comment.parentId = reply.id;
      this.message.memberId = reply.memberId;
    },
    addMycourse() {
      this.mycourse.courseId = this.courseId;
      mycourseApi.addMyCourse(this.mycourse).then((response) => {
        this.$message.success("添加成功");
        this.initCourseInfo();
      });
    },
    learnCourse() {
      let uid = "";
      if (this.loginInfo.id === "") uid = "visitor";
      else uid = this.loginInfo.id;
      courseApi.calViewCount(this.courseId, uid).then((response) => {
        console.log("增加浏览量");
      });
    },
    //浏览历史统计
    collectData() {
      if (this.loginInfo.id !== "") {
        this.history.userId = this.loginInfo.id
        this.history.title = this.courseWebVo.title
        this.history.cover = this.courseWebVo.cover
        this.history.urlPath = this.getUrlRelativePath()
        this.history.tag="课程-"+this.courseWebVo.subjectLevelTwo
        historyApi.collectHistory(this.history).then(res => {
          console.log("记录浏览历史");
        })
      }
    },
    //获取相对路径
    getUrlRelativePath() {
      const url = document.location.toString();
      const arrUrl = url.split("//");

      const start = arrUrl[1].indexOf("/");
      let relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符

      if (relUrl.indexOf("?") != -1) {
        relUrl = relUrl.split("?")[0];
      }
      return relUrl;
    },
    momentFormat(dateStr) {
      return moment(new Date(dateStr)).startOf('millisecond').fromNow()
    }
  },
};
</script>

<style lang="less" scoped>
.comment-wrapper {
  margin-top: 20px;
}

.comment-content {
  padding: 20px;
}
</style>
